import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:zhuanzu/page/chat_page.dart';
import 'package:zhuanzu/page/explore_page.dart';
import 'package:zhuanzu/page/my_page.dart';

import '../page/LoadingPage.dart';
import '../page/MainAppPage.dart';
import '../page/SettingsPage.dart';
import '../page/UserProfilePage.dart';
import '../page/login_page.dart';
import '../page/plulish_page.dart';
import '../page/post_complaint.dart';
import '../page/post_detail.dart';
import '../page/post_girl.dart';
import '../page/post_rent.dart';
import '../provider/AuthProvider.dart';

/// 全局 NavigatorKey，用于非 context 场景跳转（如 token 失效后强制跳转）
final GlobalKey<NavigatorState> globalNavigatorKey =
    GlobalKey<NavigatorState>();

/// 全局路由对象（需在 main 初始化）
late GoRouter globalRouter;

/// 初始化全局路由（必须在 main 中调用）
void initGlobalRouter(AuthProvider authProvider) {
  globalRouter = GoRouter(
    navigatorKey: globalNavigatorKey,
    initialLocation: '/',
    debugLogDiagnostics: true,
    refreshListenable: authProvider,
    // 监听登录状态变更，触发 redirect
    redirect: (context, state) {
      final loading = authProvider.isLoading;
      final loggedIn = authProvider.isLoggedIn;
      final isAtLogin = state.matchedLocation == '/login';

      print(
        '[GoRouter<<<<<----->>>> Redirect] loading=$loading, loggedIn=$loggedIn, location=${state.location}',
      );

      if (loading) return '/loading';
      if (!loggedIn && !isAtLogin) return '/login';
      if (loggedIn && isAtLogin) return '/'; // 登录后不留在登录页
      if (state.matchedLocation == '/loading' && !loading) {
        return loggedIn ? '/' : '/login';
      }

      return null;
    },
    routes: [
      GoRoute(
        path: '/',
        builder: (context, state) {
          final tab = GoRouterState.of(context).queryParameters['tab'];
          return MainAppPage(key: ValueKey(tab), tab: tab);
        },
      ),
      GoRoute(path: '/login', builder: (context, state) => const LoginPage()),
      GoRoute(
        path: '/loading',
        builder: (context, state) => const LoadingPage(),
      ),
      GoRoute(path: '/my', builder: (context, state) => const MyPage()),
      GoRoute(
        path: '/explore',
        builder: (context, state) => const ExplorePage(),
      ),

      GoRoute(
        path: '/publish',
        builder: (context, state) => const PublishPage(),
      ),
      GoRoute(
        path: '/user/:id',
        name: 'userProfile',
        builder: (context, state) {
          final userId = state.pathParameters['id']!;
          final nickname = state.queryParameters['nickname'] ?? '';
          return UserProfilePage(userId: userId, nickname: nickname);
        },
      ),
      GoRoute(
        path: '/post/:id',
        name: 'postDetail',
        builder: (context, state) {
          final postId = state.pathParameters['id']!;
          return PostDetailPage(postId: postId);
        },
      ),
      GoRoute(
        path: '/publish/rent',
        builder: (context, state) => const RentPublishPage(),
      ),
      GoRoute(
        path: '/publish/tucao',
        builder: (context, state) => const ComplaintPublishPage(),
      ),
      GoRoute(
        path: '/publish/girl',
        builder: (context, state) => const GirlPublishPage(),
      ),
      GoRoute(
        path: '/settings',
        builder: (context, state) => const SettingsPage(),
      ),
      GoRoute(
        path: '/chat',
        builder: (context, state) {
          final nickname = state.queryParameters['nickname'] ?? '未知用户';
          final userId = state.queryParameters['userId'] ?? '';
          final myId = state.queryParameters['myId'] ?? '';
          return ChatPage(nickname: nickname, userId: userId, myId: myId);
        },
      ),
    ],
  );
}
